/**
 * 请求参数token失效的情况判断
 * @param {String} Message 402返回的参数
 * @returns {Promise} 是否需要再次请求
 */
import axios from "axios"
import { Message as Messages } from 'element-ui'
import { showLoading, hideLoading } from '@/utils/loading'


const refreshtokenFunc = function refreshtoken (Message) {
    return new Promise((resolve, reject) => {
        if (Message == 'expired') {
            const url = '/api/Login/RefreshToken'
            const data = {
                token: $cookies.get('totalInfo').UserInfo.Token,
                refreshToken: $cookies.get('totalInfo').UserInfo.RefreshToken
            }
            showLoading()// 加载
            axios({
                method: 'POST',
                url,
                baseURL: process.env.VUE_APP_URL,
                data: data,
            })
                .then(response => {
                    console.log(response, 'response');
                    let res = response.data
                    hideLoading()// 停止加载
                    if (res.Code == 200) {
                        // 取值
                        let getToatalInfo = $cookies.get('totalInfo')
                        let getUserInfo = getToatalInfo.UserInfo
                        getUserInfo.Token = res.Data.Token
                        getUserInfo.RefreshToken = res.Data.RefreshToken
                        // 存值
                        $cookies.set('totalInfo', getToatalInfo, '7d', '/')
                        this.$store.commit('updateToken', getUserInfo.Token)
                        resolve(true)
                    } else {
                        console.log('调用RefreshToken 接口失败');
                        Messages({
                            type: 'error',
                            message: '登录过期，请重新登录',
                        })
                        resolve(false)
                    }
                }).catch(err => {
                    hideLoading()// 停止加载
                    console.log('refreshtoken请求报错：', err);
                    reject(err)
                })
        } else {
            console.log('非expired退出登录');
            Messages({
                type: 'error',
                message: '登录过期，请重新登录',
            })
            resolve(false)
        }
    })

}

const refreshTokenData = {
    install (Vue) {
        Vue.prototype.refreshtokenfunc = refreshtokenFunc
    }
}

export default refreshTokenData